package vip.xiaomoli.courier.component;

import vip.xiaomoli.courier.dao.CourierDao;
import vip.xiaomoli.courier.model.Result;
import vip.xiaomoli.courier.model.TaskInfo;
import vip.xiaomoli.courier.service.Courier;
import vip.xiaomoli.courier.util.ApplicationContextHelper;

import java.util.Date;

public class CourierExecutor {

    public static void execute(TaskInfo ti, CourierDao dao) {
        Date execBgnTime = new Date();
        Result result = null;
        try {
            Class<?> clazz = Class.forName(ti.getCourierName());
            Courier courier = (Courier) ApplicationContextHelper.getBean(clazz);
            if (null == courier) {
                result = Result.fail(ti.getCourierName() + " not in spring context.");
            } else {
                result = courier.execute(ti.getParam(), 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = Result.fail(e.toString());
        } finally {
            ti.setExecBgnTime(execBgnTime);
            ti.setExecEndTime(new Date());
            ti.setExecMillis(ti.getExecEndTime().getTime() - ti.getExecBgnTime().getTime());
            assert result != null;
            if (Result.FAILURE == result.getFlag()) {
                ti.setFailMessage(result.getFailMessage());
                ti.setFailTimes(ti.getFailTimes()+1);
                dao.recordExecFail(ti);
            } else {
                dao.recordExecSuccess(ti);
            }
        }
    }

}
